/**
 * 队列管理器 - 负责弹幕队列的管理
 */
import type { BarrageItem, ActiveBarrage } from '../../types'

export class QueueManager {
  private maxBarrages: number
  private barrageQueue: BarrageItem[] = []
  private activeBarrages: ActiveBarrage[] = []
  private barrageIdMap: Map<string, ActiveBarrage> = new Map()

  constructor(maxBarrages: number = 50) {
    this.maxBarrages = maxBarrages
  }

  /**
   * 添加到队列
   */
  addToQueue(barrage: BarrageItem): void {
    this.barrageQueue.push(barrage)
  }

  /**
   * 从队列获取下一个弹幕
   */
  getNextFromQueue(): BarrageItem | null {
    return this.barrageQueue.shift() || null
  }

  /**
   * 添加活跃弹幕
   */
  addActiveBarrage(barrage: ActiveBarrage): void {
    this.activeBarrages.push(barrage)
    this.barrageIdMap.set(barrage.id, barrage)
  }

  /**
   * 移除活跃弹幕
   */
  removeActiveBarrage(barrage: ActiveBarrage): void {
    const index = this.activeBarrages.indexOf(barrage)
    if (index !== -1) {
      this.activeBarrages.splice(index, 1)
    }
    this.barrageIdMap.delete(barrage.id)
  }

  /**
   * 通过ID获取弹幕
   */
  getBarrageById(id: string): ActiveBarrage | undefined {
    return this.barrageIdMap.get(id)
  }

  /**
   * 获取队列长度
   */
  getQueueLength(): number {
    return this.barrageQueue.length
  }

  /**
   * 获取活跃弹幕数量
   */
  getActiveCount(): number {
    return this.activeBarrages.length
  }

  /**
   * 获取所有活跃弹幕
   */
  getAllActive(): ActiveBarrage[] {
    return this.activeBarrages
  }

  /**
   * 检查是否已满
   */
  isFull(): boolean {
    return this.activeBarrages.length >= this.maxBarrages
  }

  /**
   * 清空队列
   */
  clearQueue(): void {
    this.barrageQueue = []
  }

  /**
   * 清空活跃弹幕
   */
  clearActive(): void {
    this.activeBarrages = []
    this.barrageIdMap.clear()
  }

  /**
   * 清空所有
   */
  clearAll(): void {
    this.clearQueue()
    this.clearActive()
  }

  /**
   * 更新最大容量
   */
  updateMaxCapacity(max: number): void {
    this.maxBarrages = max
  }

  /**
   * 获取队列状态
   */
  getStatus(): { queueLength: number; activeCount: number; maxCount: number } {
    return {
      queueLength: this.barrageQueue.length,
      activeCount: this.activeBarrages.length,
      maxCount: this.maxBarrages
    }
  }
}

